package pl.edu.pw.perg.compinfodb.datamodel;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import pl.edu.pw.perg.compinfodb.entities.ElementType;
import pl.edu.pw.perg.compinfodb.entities.PhysicalElement;
import pl.edu.pw.perg.compinfodb.entities.VirtualElement;
import pl.edu.pw.perg.compinfodb.manager.IPhysicalElementManager;

// lista ma trzymac calosc danych.
// zawiera tez tymczasowa liste przefiltrowana.
// jesli tymczasowa lista sie zmieni, mozliwosc komitu zmian.
// Przy inicjalizacji opakowanie wszystkich elementow listy tymczasowej.

public class ElementDataList {

	private IPhysicalElementManager elementManager;
	private List<PhysicalElement> persistentList;
	private List<TableData> temporaryList = new ArrayList<TableData>();
	private List<VirtualElement> veFilter = new ArrayList<VirtualElement>();
	private ElementType typeFilter;
	private Map<Integer, String> stringFilters;

	public ElementDataList(IPhysicalElementManager elementManager) {
		this.elementManager = elementManager;
		persistentList = elementManager.findAll();
		search();
	}

	public TableData get(int index) {
		if (index >= temporaryList.size() || index < 0)
			return null;
		return temporaryList.get(index);
	}

	public void search(){
		search(null);
	}
	
	public void search(Map<String, String> filter) {
		// throw new RuntimeException("Wywolanie ElementDataList.search()");
		temporaryList.clear();
		List<PhysicalElement> tmp = new LinkedList<PhysicalElement>();
		List<PhysicalElement> toRemove = new LinkedList<PhysicalElement>();
		tmp.addAll(persistentList);

		// TODO: o co tu kaman?
		// if(!veFilter.isEmpty()){
		// for (PhysicalElement pe : tmp) {
		// if(!veFilter.contains(pe.getVirtualElement()))
		// toRemove.add(pe);
		// }
		// tmp.removeAll(toRemove);
		// toRemove.clear();
		// }
		if (typeFilter != null) {
			for (PhysicalElement pe : tmp) {
				if (!pe.getElementType().equals(typeFilter))
					toRemove.add(pe);
			}
			tmp.removeAll(toRemove);
		}
		for (PhysicalElement pe : tmp) {
			TableData td = new TableData(pe);
			if(td.matchesFilter(filter))
				temporaryList.add(td);
		}

	}

	public int size() {
		return temporaryList.size();
	}

	public void setTypeFilter(ElementType typeFilter) {
		this.typeFilter = typeFilter;
	}
}